package com.ghck.server.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ghck.server.dao.KnowledgeMapper;
import com.ghck.server.exception.GhckException;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.Knowledge;
import com.ghck.server.model.request.KnowledgeReq;
import com.ghck.server.model.response.KnowledgeRes;
import com.ghck.server.service.KnowledgeService;
import com.ghck.server.utils.FileStoreUtil;

@Service
@Transactional
public class KnowledgeServiceImpl implements KnowledgeService{

	@Autowired
	private KnowledgeMapper knowledgeMapper;
	
	@Override
	public List<KnowledgeRes> list(Knowledge knowledge,Integer start,Integer limit) {
		KnowledgeReq knowledgeReq = null;
		if(knowledge instanceof KnowledgeReq){
			knowledgeReq = (KnowledgeReq) knowledge;
		}
		knowledgeReq.setStart(start);
		knowledgeReq.setLimit(limit);
		List <KnowledgeRes> list = knowledgeMapper.list(knowledgeReq);
		for(KnowledgeRes res : list){
			if(null != res.getPicUrl() && !res.getPicUrl().isEmpty()){
				res.setPicUrl(FileStoreUtil.getBaseUrl().concat(res.getPicUrl()));
			}
			res.setContent(null);
		}
		return list;
	}

	@Override
	public KnowledgeRes detail(Knowledge knowledge) {
		
		return knowledgeMapper.detail(knowledge);
	}

	@Override
	public Knowledge add(Knowledge knowledge) {
		
		if(knowledge.getTitle() == null || knowledge.getTitle().isEmpty()){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "标题不能为空");
		}
		if(knowledge.getContent() == null || knowledge.getContent().isEmpty()){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "内容不能为空");
		}
		if(knowledge.getPublishTime() == null){
			knowledge.setPublishTime(new Date());
		}
		knowledgeMapper.add(knowledge);
		return knowledge;
	}

	@Override
	public void delete(Knowledge knowledge) {
		if(knowledge.getId() == null){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "文章ID不能为空");
		}
		knowledgeMapper.delete(knowledge);
	}

	@Override
	public void update(Knowledge knowledge) {
		
	}

}
